import React, { useEffect, useState } from 'react';
import { Table, Tag, Space, Button, Modal, Form, Input, message } from 'antd';
import { request } from 'umi'

// add button's modal window
const CollectionCreateForm = ({ visible, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
        <Modal
            visible={visible}
            title="增加"
            okText="确定"
            cancelText="取消"
            onCancel={onCancel}
            onOk={() => {
                form.validateFields().then((values) => {
                    form.resetFields();
                    onCreate(values);
                })
                    .catch((info) => {
                        console.log('Validate Failed:', info);
                    });
            }}
        >
            <Form
                form={form}
                layout="vertical"
                name="form_in_modal"
                initialValues={{
                    modifier: 'public',
                }}
            >
                <Form.Item name="index" label="序号">
                    <Input />
                </Form.Item>
                <Form.Item name="name" label="名称">
                    <Input type="textarea" />
                </Form.Item>
            </Form>
        </Modal>
    );
};


const DishClass = () => {
    const [propObj, setPropObj] = useState({});
    // 编辑功能的弹出框
    const EditForm = ({ visible, onCreate, onCancel }) => {
        const [form] = Form.useForm();
        return (
            <Modal
                visible={visible}
                title="编辑"
                okText="确定"
                cancelText="取消"
                onCancel={onCancel}
                onOk={() => {
                    form.validateFields().then((values) => {
                        form.resetFields();
                        onCreate(values);
                    })
                        .catch((info) => {
                            console.log('Validate Failed:', info);
                        });
                }}
            >
                <Form
                    form={form}
                    layout="vertical"
                    name="form_in_modal"
                    initialValues={{
                        modifier: 'public',
                        index: propObj.index,
                        name: propObj.name
                    }}
                >
                    <Form.Item name="index" label="序号">
                        <Input />
                    </Form.Item>
                    <Form.Item name="name" label="名称">
                        <Input type="textarea" />
                    </Form.Item>
                </Form>
            </Modal>
        );
    };

    // hook
    const [list, setList] = useState([])

    const getData = () => {
        request("http://www.young1024.com:1717/v1/serie/list").then(
            (res) => {
                setList(res.data)
            },
            (err) => { console.log(err); }
        )
    }

    useEffect(() => {
        getData()
    }, [])

    // form's data
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            render: text => <a>{text}</a>,
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    <Button type="primary" onClick={() => { handleEdit(text._id) }}>
                        编辑
                    </Button>
                    <Button type="primary" danger onClick={() => { handleDelete(text._id) }}>
                        删除
                    </Button>
                </Space>
            ),
        },
    ];
    // 删除功能
    const handleDelete = (id) => {
        let param = new URLSearchParams;
        param.append("id", id);
        request("http://www.young1024.com:1717/v1/serie/del", { data: param }).then(
            (res) => {
                console.log(res);
                if (res.status === "success") {
                    getData();
                    message.info('删除成功');
                }
            },
            (err) => {
                console.log(err);
            }
        )
    }

    //创建增加表单
    const [visible, setVisible] = useState(false);
    const onCreate = (values) => {
        console.log('Received values of form: ', values);
        const param = new URLSearchParams;
        if (values.index) {
            param.append("index", values.index)
        }
        param.append("name", values.name)
        request("http://www.young1024.com:1717/v1/serie/add", { data: param }).then(
            (res) => {
                if (res.status === "success") {
                    getData();
                    message.info('添加成功');
                }
            },
            (err) => { console.log(err); }
        )
        setVisible(false);
    };

    // 编辑功能
    const [visible_edit, setVisible_edit] = useState(false);
    const handleEdit = (id) => {
        request("http://www.young1024.com:1717/v1/serie/list").then(
            (res) => {
                let obj = res.data.find(item => item._id === id);
                obj["id"] = id;
                setPropObj(obj)
                setVisible_edit(true)
            },
            (err) => { console.log(err); }
        )
    }

    //创建编辑表单功能
    const onCreate_edit = (values) => {
        console.log('Received values of form: ', values);
        const param = new URLSearchParams;
        param.append("id",propObj.id)
        param.append("index",values.index)
        param.append("name",values.name)
        request("http://www.young1024.com:1717/v1/serie/update", { data: param }).then(
            (res) => {
                console.log(res);
                if (res.status === "success") {
                    getData();
                    message.info('添加成功');
                    setVisible_edit(false);
                }
            },
            (err) => { console.log(err); }
        )
    };

    //
    return (
        <div style={{ padding: "20px 20px", height: "100%" }}>
            <div style={{ background: "white", minHeight: "500px", padding: "20px" }}>
                <h2>菜品分类管理</h2>
                <Table columns={columns} dataSource={list} rowKey={record => record._id} />
                <Button type="primary" onClick={() => { setVisible(true) }}>添加</Button>
                <CollectionCreateForm
                    visible={visible}
                    onCreate={onCreate}
                    onCancel={() => {
                        setVisible(false);
                    }}
                />
                <EditForm
                    visible={visible_edit}
                    onCreate={onCreate_edit}
                    onCancel={() => {
                        setVisible_edit(false);
                    }}
                />
            </div>

        </div>
    );
}
export default DishClass;
